import time
import json
from influxdb import InfluxDBClient

HOST = "119.23.73.197"
PORT = "8086"
USER = "admin"
PASSWORD = "123456"
DB = "mytest"

influxCli = InfluxDBClient(HOST,PORT,USER,PASSWORD, DB)

class InfluxdbTool:
    def __init__(self):
        self.influxCli = InfluxDBClient(HOST,PORT,USER,PASSWORD, DB)
        self.points = []

    def append_points(self, time, appid, expType, expCnt, netType, expDomain, browserType):
        try:
            point = {}
            point.update({"measurement": "frontendExpCount"})
            point.update({"time": int(time) * 1000 * 1000 * 1000})
            tags = {}
            tags.update({"appid": appid})
            tags.update({"expType": expType})
            tags.update({"netType": netType})
            tags.update({"browserType": browserType})
            point.update({"tags": tags})

            fields = {}
            fields.update({"expCnt": int(expCnt)})
            fields.update({"domain": expDomain})
            point.update({"fields": fields})
            self.points.append(point)
        except Exception as e:
            print("append_points err,", time, appid, expType, expCnt, netType, expDomain, browserType)

    def execute_insert(self):
        try:
            self.influxCli.write_points(self.points)
            print("insert points cnt=",len(self.points))
        except Exception as e:
            print("insert influxdb err, points=", self.points)
        finally:
            self.points = []
    def close(self):
        if self.influxCli:
            influxCli.close()



